﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;

namespace BluePortal.Medias.Core
{
    public class BCVideo : BCMedia<Video>
    {
        public void Create(Video media)
        {
            if (media.ID == Guid.Empty) media.ID = Guid.NewGuid();
            media.Rating = 0;
            media.PublishDate = DateTime.Now;
            media.Status = (int)MediaStatus.Creation;
            Context.Medias.InsertOnSubmit(media);
            Context.SubmitChanges();
        }

        public void Update(Video v)
        {
            var query = Context.Videos.SingleOrDefault(m => m.ID == v.ID);
            if (query != null)
            {
                query.Description = v.Description;
                query.Preview = v.Preview;
                query.Status = v.Status;
                query.Title = v.Title;
                query.Provider = v.Provider;
                query.ProviderOptions = v.ProviderOptions;
                query.Duration = v.Duration;
                query.Height = v.Height;
                query.Width = v.Width;
                query.Rating = v.Rating;
                query.IsPrivate = v.IsPrivate;
                query.ParentalRating = v.ParentalRating;
                query.FileSize = v.FileSize;
                Context.SubmitChanges();
            }
        }

        //public Media FindByIDWithOtherVideoAttachs(Guid ID)
        //{
        //    Media v = (Media)FindByID(ID);

        //    var q = from ova in Context.OtherVideoAttaches where ova.ID == v.ID orderby ova.FormatId select ova;
        //    foreach(OtherVideoAttach o in q)
        //    {
        //        v.OtherVideoAttaches.Add(o);
        //    }

        //    return v;
        //}

        public void CreateOrUpdate(Video video)
        {
            using (TransactionScope tr = new TransactionScope())
            {
                var query = Context.Medias.SingleOrDefault(v => v.ID == video.ID);
                if (query != null)
                {
                    Update(video);
                }
                else
                {
                    Create(video);
                }
                tr.Complete();
            }
        }

        public Video FindVideoByID(Guid id) { 
            return Context.Videos.SingleOrDefault(v => v.ID == id); 
        }
    }
}
